<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="关联系统用户ID" prop="sysUserId">
        <el-input
          v-model="queryParams.sysUserId"
          placeholder="请输入关联系统用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="投票昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入投票昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:voteUser:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:voteUser:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:voteUser:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:voteUser:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="voteUserList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="投票用户ID" align="center" prop="id" />
      <el-table-column label="关联系统用户ID" align="center" prop="sysUserId" />
      <el-table-column label="投票昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="phone" />

      <el-table-column label="是否匿名投票" align="center" prop="isAnonymous">
        <template #default="scope">
          {{ scope.row.isAnonymous ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:voteUser:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:voteUser:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改投票用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="voteUserRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <!-- 用户类型选择 -->
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group
            v-model="form.userType"
            @change="handleUserTypeChange"
          >
            <el-radio :label="1">系统内用户</el-radio>
            <el-radio :label="2">外部访客</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 系统用户选择（用户类型为系统内用户时显示） -->
        <el-form-item
          label="系统用户"
          prop="sysUserId"
          v-if="form.userType == 1"
        >
          <el-select
            v-model="form.sysUserId"
            placeholder="请输入手机号"
            clearable
            filterable
            style="width: 100%"
            remote
            reserve-keyword
            :remote-method="getRemoteUserList"
            :loading="sysUserLoading"
          >
            <el-option
              v-for="user in sysUserList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <!-- 外部用户信息（用户类型为外部访客时显示） -->
        <el-form-item
          label="访客昵称"
          prop="nickname"
          v-if="form.userType == 2"
        >
          <el-input v-model="form.nickname" placeholder="请输入访客昵称" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone" v-if="form.userType == 2">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <!-- 公共属性 -->
        <el-form-item label="是否匿名" prop="isAnonymous">
          <el-switch
            v-model="form.isAnonymous"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VoteUser">
import {
  listVoteUser,
  getVoteUser,
  delVoteUser,
  addVoteUser,
  updateVoteUser,
} from "@/api/business/voteUser";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();

const voteUserList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);

const data = reactive({
  form: {
    userType: 1, // 1-系统内用户 2-外部访客
    sysUserId: null,
    nickname: null,
    phone: null,
    isAnonymous: 0,
    remark: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sysUserId: null,
    nickname: null,
    phone: null,
    isAnonymous: null,
    optionContent: null,
  },
  rules: {
    nickname: [
      { required: true, message: "投票昵称不能为空", trigger: "blur" },
    ],
    phone: [{required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    sysUserId: { required: true, message: "系统用户不能为空", trigger: "blur" },
  },
});

const { queryParams, form, rules } = toRefs(data);
const sysUserList = ref([]);
const sysUserLoading = ref(false);
const sysUserQueryParams = ref({
  pageNum: 1,
  pageSize: 50,
  phonenumber: null,
});

/** 查询系统用户列表 */
function getRemoteUserList(query) {
  if (query) {
    sysUserLoading.value = true;
    sysUserQueryParams.value.phonenumber = query;
    listUser(sysUserQueryParams.value)
      .then((res) => {
        sysUserLoading.value = false;
        sysUserList.value = res.rows;
        sysUserLoading.value = false;
      })
      .catch((err) => {
        sysUserLoading.value = false;
      })
      .finally(() => {
        sysUserLoading.value = false;
      });
  } else {
    sysUserList.value = [];
  }
}
/** 查询投票用户列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listVoteUser(queryParams.value).then((response) => {
    voteUserList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sysUserId: null,
    nickname: null,
    phone: null,
    isAnonymous: null,
    createTime: null,
  };
  proxy.resetForm("voteUserRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.userType = 1;
  title.value = "添加投票用户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getVoteUser(_id).then((response) => {
    form.value = response.data;
    console.log( form.value)
    form.value.userType = response.data.sysUserId ? 1 : 2;
    open.value = true;
    title.value = "修改投票用户";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["voteUserRef"].validate((valid) => {
    if (valid) {
      console.log('form.value')
      form.value.isAnonymous = form.value.isAnonymous ? 1 : 0;
      if(form.value.userType == 1){//系统用户
        sysUserList.value.forEach(item => {
          if(item.userId == form.value.sysUserId){
            form.value.nickname = item.userName;
            form.value.phone = item.phonenumber;
          }
        })
      }
      else{

      }
      if (form.value.id != null) {
        updateVoteUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        console.log(form.value)
        addVoteUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除投票用户编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delVoteUser(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/voteUser/export",
    {
      ...queryParams.value,
    },
    `voteUser_${new Date().getTime()}.xlsx`
  );
}
function handleUserTypeChange(value) {
  if (form.value.userType == 1) {
    //系统用户
    form.value.nickname = null;
    form.value.phone = null;
    form.value.sysUserId = null;
  } else {
    form.value.sysUserId = null;
  }
  proxy.resetForm("queryRef");
}

getList();
</script>
